package com.jueling.culture.core.filter;

import lombok.Data;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linp
 * @date 2022/02/16
 */
@Data
@WebFilter
@Configuration
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //跨域设置
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String originHeader=req.getHeader("Origin");
        response.setCharacterEncoding("UTF-8");
        res.setHeader("Content-type", "application/json;charset=UTF-8");
        res.setHeader("Access-Control-Expose-Headers", "system_time");
        res.setHeader("Access-Control-Allow-Origin",originHeader);
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET,PUT, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Referer,Authorization,refresh_token,system_time,time_stamp,version,app_id,sign");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
